<template>
  <div class="email-verification-page">
    <div class="verification-container">
      <!-- Header -->
      <div class="header">
        <van-nav-bar title="Email Verification" left-text="Back" left-arrow @click-left="$router.back()" />
      </div>

      <div class="content">
        <!-- Verification Pending -->
        <div v-if="!isVerified" class="verification-pending">
          <div class="step-header">
            <van-icon name="envelop-o" class="step-icon" />
            <h2 class="step-title">Verify your email</h2>
            <p class="step-description">
              We've sent a verification link to <strong>{{ userEmail }}</strong>
            </p>
          </div>

          <div class="verification-instructions">
            <div class="instruction-item">
              <van-icon name="info-o" />
              <span>Click the link in the email to verify your account</span>
            </div>
            <div class="instruction-item">
              <van-icon name="clock-o" />
              <span>The link will expire in 24 hours</span>
            </div>
          </div>

          <div class="verification-actions">
            <van-button round block type="primary" :loading="checkingLoading" @click="checkVerificationStatus"
              class="check-btn">
              I've verified my email
            </van-button>

            <div class="resend-section">
              <p>Didn't receive the email?</p>
              <van-button type="primary" plain size="small" :loading="resendLoading" :disabled="resendCooldown > 0"
                @click="handleResendEmail" class="resend-btn">
                {{ resendCooldown > 0 ? `Resend in ${resendCooldown}s` : 'Resend email' }}
              </van-button>
            </div>
          </div>
        </div>

        <!-- Verification Success -->
        <div v-else class="verification-success">
          <div class="step-header">
            <van-icon name="success" class="step-icon success" />
            <h2 class="step-title">Email verified!</h2>
            <p class="step-description">
              Your email has been successfully verified. You can now access all features.
            </p>
          </div>

          <div class="form-actions">
            <van-button round block type="primary" @click="$router.push('/')" class="continue-btn">
              Continue to App
            </van-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { authApi } from '@/api/auth'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const isVerified = ref(false)
const checkingLoading = ref(false)
const resendLoading = ref(false)
const resendCooldown = ref(0)
const userEmail = ref('')

let cooldownTimer: number | null = null

onMounted(async () => {
  // Get user email from store or route params
  userEmail.value = userStore.userInfo?.email || (route.query.email as string) || ''

  // Check if there's a verification token in the URL
  const token = route.query.token as string
  if (token) {
    await verifyEmailWithToken(token)
  }
})

onUnmounted(() => {
  if (cooldownTimer) {
    clearInterval(cooldownTimer)
  }
})

const verifyEmailWithToken = async (token: string) => {
  try {
    checkingLoading.value = true
    await authApi.verifyEmail(token)

    isVerified.value = true
    showToast({
      type: 'success',
      message: 'Email verified successfully'
    })

  } catch (error: any) {
    showToast({
      type: 'fail',
      message: error.message || 'Email verification failed'
    })
  } finally {
    checkingLoading.value = false
  }
}

const checkVerificationStatus = async () => {
  try {
    checkingLoading.value = true
    const response = await authApi.checkEmailVerification()

    if (response.data?.isVerified) {
      isVerified.value = true
      showToast({
        type: 'success',
        message: 'Email verified successfully'
      })
    } else {
      showToast({
        type: 'fail',
        message: 'Email not verified yet. Please check your email.'
      })
    }

  } catch (error: any) {
    showToast({
      type: 'fail',
      message: error.message || 'Failed to check verification status'
    })
  } finally {
    checkingLoading.value = false
  }
}

const handleResendEmail = async () => {
  try {
    resendLoading.value = true
    await authApi.resendVerificationEmail(userEmail.value)

    showToast({
      type: 'success',
      message: 'Verification email sent'
    })

    // Start cooldown
    startResendCooldown()

  } catch (error: any) {
    showToast({
      type: 'fail',
      message: error.message || 'Failed to resend email'
    })
  } finally {
    resendLoading.value = false
  }
}

const startResendCooldown = () => {
  resendCooldown.value = 60
  cooldownTimer = setInterval(() => {
    resendCooldown.value--
    if (resendCooldown.value <= 0) {
      clearInterval(cooldownTimer!)
      cooldownTimer = null
    }
  }, 1000)
}
</script>

<style lang="scss" scoped>
.email-verification-page {
  min-height: 100vh;
  background: $background-color;
}

.verification-container {
  max-width: 400px;
  margin: 0 auto;
  background: $white;
  min-height: 100vh;
}

.header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: $white;
  border-bottom: 1px solid $border-color;
}

.content {
  padding: $spacing-lg;
}

.step-header {
  text-align: center;
  margin-bottom: $spacing-xl;

  .step-icon {
    font-size: 48px;
    color: $primary-color;
    margin-bottom: $spacing-md;

    &.success {
      color: $success-color;
    }
  }

  .step-title {
    font-size: $font-size-xl;
    font-weight: $font-weight-bold;
    color: $text-color;
    margin-bottom: $spacing-sm;
  }

  .step-description {
    font-size: $font-size-md;
    color: $text-color-3;
    line-height: 1.5;
  }
}

.verification-instructions {
  margin: $spacing-xl 0;

  .instruction-item {
    display: flex;
    align-items: center;
    margin-bottom: $spacing-md;
    padding: $spacing-sm;
    background: $gray-1;
    border-radius: $border-radius-md;

    .van-icon {
      color: $primary-color;
      margin-right: $spacing-sm;
      font-size: $font-size-lg;
    }

    span {
      font-size: $font-size-sm;
      color: $text-color-2;
    }
  }
}

.verification-actions {
  .check-btn {
    height: 48px;
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    margin-bottom: $spacing-lg;
  }

  .resend-section {
    text-align: center;

    p {
      font-size: $font-size-sm;
      color: $text-color-3;
      margin-bottom: $spacing-sm;
    }

    .resend-btn {
      font-size: $font-size-sm;

      &:disabled {
        opacity: 0.5;
      }
    }
  }
}

.form-actions {
  margin: $spacing-xl 0;

  .continue-btn {
    height: 48px;
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
  }
}

.password-strength {
  margin: $spacing-sm 0;
  padding: 0 $spacing-md;

  .strength-bar {
    height: 4px;
    background: $gray-3;
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: $spacing-xs;

    .strength-fill {
      height: 100%;
      transition: width 0.3s ease;

      &.weak {
        background: $danger-color;
      }

      &.medium {
        background: $warning-color;
      }

      &.strong {
        background: $success-color;
      }
    }
  }

  .strength-text {
    font-size: $font-size-xs;
    color: $text-color-3;
    text-transform: capitalize;
  }
}
</style>